package com.qf.java2102.qihaonan.hotel.controller.cart;

import com.qf.java2102.qihaonan.hotel.entity.CartItem;
import com.qf.java2102.qihaonan.hotel.pojo.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author qhn
 * @version 1.0
 */
@WebServlet("/cart/add")
public class CartAddController extends HttpServlet {

    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.foodId
        String foodIdStr = request.getParameter("foodId");
        Long foodId = Long.valueOf(foodIdStr);

        //2.获取餐车
        HttpSession session = request.getSession();
        User frontUser = (User) session.getAttribute("frontUser");
        if(frontUser == null) {

            response.getWriter().write("loginError");
            return;
        }
        Map<Long, CartItem> cart = (Map<Long, CartItem>) session.getAttribute(frontUser.getUserId()+"");

        //判断餐车是否存在?
        if(cart == null) {
            cart = new HashMap<>();
            CartItem cartItem = new CartItem();
            cartItem.setFoodId(foodId);
            cartItem.setNum(1);
            cartItem.setUpdateTime(new Date());

            //放入到餐车中
            cart.put(cartItem.getFoodId(), cartItem);
        } else {
            if (cart.containsKey(foodId)) {
                //餐车中有这个菜
                CartItem cartItem = cart.get(foodId);
                cartItem.setNum( cartItem.getNum() + 1);
                cartItem.setUpdateTime(new Date());
            } else {
                CartItem cartItem = new CartItem();
                cartItem.setFoodId(foodId);
                cartItem.setNum(1);
                cartItem.setUpdateTime(new Date());
                //放入到餐车中
                cart.put(cartItem.getFoodId(), cartItem);
            }
        }

        session.setAttribute(frontUser.getUserId()+"", cart);


        response.getWriter().write("加入餐车成功:"+ foodId);

    }

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
